<?php
include 'config/config.php';

function size_human_read ($size) {
    $sizes = array('B', 'KB', 'MB', 'GB');
    $prev_s = end($sizes);	// tro den phan tu cuoi cung la GB
    foreach ($sizes as $s) {
        if ($size < 1024) {
            break;
        }
        if ($s != $prev_s) {
            $size /= 1024;
        }
    }
    if ($s == $sizes[0]) {
        return sprintf('%01d %s', $size, $s);
    } else {
        return sprintf('%01.2f %s', $size, $s);
    }
}

// tra lai hien thi cho tung hang
function directory_row ($file, $show_stats = true) {
    $is_dir = is_dir($file);

    // Theo doi so hang de luan phien odd/even
    static $row_count;
    if (!isset($row_count)) {
        $row_count = 1;
    } else {
        $row_count++;
    }

    ob_start();
    echo '<tr class="' . ($row_count%2 == 0 ? 'evenrow':'oddrow') . '" ';
    echo 'onmouseover="highlightTableRow(this);" ';
    echo 'onmouseout="unhighlightTableRow(this)" ';
    echo 'onclick="selectTableRow(\'' . basename($file) . '\', this);" ';
    echo '>';

    // xac dinh icon thich hop de hien thi cung voi file
    echo '<td style="width:25px; text-align: center;">';
    echo '<img style="height: 16px; width: 16px;" src="img/';
    if ($is_dir && basename($file) == '..') {
        echo 'up';
    } else if ($is_dir) {
        echo 'dir';
    } else {
        $ext = substr($file, strrpos($file, '.') + 1);	// nhan lai ten file
        if (file_exists('img/' . $ext . '.gif')) {
            echo $ext;
        } else {
            echo 'unknown';
        }
    }
    echo '.gif" /></td>';

    // hien thi thong tin ve file
    echo '<td>' . basename($file) . '</td>';
    if ($show_stats) {
		$info = stat($file);  // lay thong tin ve bien $file
        echo '<td>';
        if ($is_dir) {
            echo '---';
        } else {
            echo size_human_read($info['size']);
        }
        echo '</td>';
        echo '<td>' . date('m/d/Y', $info['mtime']) . '</td>';
    } else {
        echo '<td>&nbsp;</td><td>&nbsp;</td>';
    }
    echo '</tr>';
    $r = ob_get_contents();
    ob_end_clean();

    return $r;
}

if (!isset($_GET['action'])) return;
switch ($_GET['action']) {
    // Tra lai cau truc cac file va thu muc hien thi duoi dang bang HTML
    case 'list':
        if (!isset($_GET['dir'])) return;
		
		// Ngan chan nguoi dung di tu ben ngoai thu muc goc
        $directory = realpath(BASEDIR . $_GET['dir']);
        if (strpos($directory, BASEDIR) !== 0) return;
        
		$ds = array();  // thu muc
        $fs = array();  // file

		// Nhan lai danh sach cac file va thu muc
        if ($dir = opendir($directory)) {
            while($file = basename(readdir($dir))) {
                if($file == '.' || $file == '..') {
                    continue;
                }
                if (is_dir($directory . '/' . $file)) {
                    $ds[] = $file;
                } else if (is_file($directory . '/' . $file)) {
                    $fs[] = $file;
                }
            }
            closedir($dir);
        }
        natcasesort($ds);
        natcasesort($fs);
?>
<table>
	<thead>
		<tr><th colspan="2">File/Folder</th><th>Size</th><th>Date</th></tr>
	</thead>
	<tbody>
<?php
        // Không hiển thị ..  cho thư mục gốc
        if (BASEDIR != $directory) {
            echo directory_row('..');
        }

        foreach ($ds as $d) {
            echo directory_row($directory . '/' . $d);
        }
        foreach ($fs as $file) {
            echo directory_row($directory . '/' . $file);
        }
?>
    </tbody>
</table>
<?php
        break;

    // delete a directory or file
    case 'delete':
        if (!isset($_GET['dir']) || !isset($_GET['file'])){
            return;
        }
		// Ngan chan nguoi dung di tu ben ngoai thu muc goc
        $directory = realpath(BASEDIR . $_GET['dir']);
        if (strpos($directory, BASEDIR) !== 0) {
            return;
        }
    
        $target = $directory . '/' . $_GET['file'];
    
        if (file_exists($target)) {
            if (is_dir($target) && @rmdir($target)) {
                echo 'OK';
            } else if (is_file($target) && @unlink($target)) {
                echo 'OK';
            } else {
                echo 'ERROR';
            }
        } else {
            echo 'ERROR';
        }
        break;
    
    // rename a directory or file
    case 'rename':
        if (!isset($_GET['dir']) || !isset($_GET['oldfile']) || !isset($_GET['newfile'])) {
            return;
        }
        // Ngan chan nguoi dung di tu ben ngoai thu muc goc
        $directory = realpath(BASEDIR . $_GET['dir']);
        if (strpos($directory, BASEDIR) !== 0) {
            return;
        }
    
        $old = $directory . '/' . $_GET['oldfile'];
        $new = $directory . '/' . $_GET['newfile'];
    
        if (file_exists($old) && @rename($old, $new)) {
            echo 'OK';
        } else {
            echo 'ERROR';
        }
        break;
    
    // create a new directory
    case 'new':
        if (!isset($_GET['dir']) || !isset($_GET['name'])) {
            return;
        }
        // Ngan chan nguoi dung di tu ben ngoai thu muc goc
        $directory = realpath(BASEDIR . $_GET['dir']);
        if (strpos($directory, BASEDIR) !== 0) {
            return;
        }
    
        $target = $directory . '/' . $_GET['name'];
    
        if (!file_exists($target) && @mkdir($target)) {
            echo 'OK';
        } else {
            echo 'ERROR';
        }
        break;
    
    // Trả lại thông tin cần thiết để mở thư mục hoặc tải file về
    case 'open':
        if (!isset($_GET['dir']) || !isset($_GET['file'])){
            return;
        }
        // Ngan chan nguoi dung di tu ben ngoai thu muc goc
        $directory = realpath(BASEDIR . $_GET['dir']);
        if (strpos($directory, BASEDIR) !== 0) {
            return;
        }
    
        $target = $directory . '/' . $_GET['file'];
    
        if (file_exists($target)) {
            if (is_file($target)) {
                echo json_encode(array('retType' => 'file'));
            } else if (is_dir($target)) {
                echo json_encode(array('retType' => 'directory',
									   'directory' => substr($target, strlen(BASEDIR))));
            }
        }
        break;
}
?>